#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import logging
import os
import pytz
from fastapi import FastAPI, Depends, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from fastapi.exceptions import RequestValidationError
import time

# 设置时区
os.environ['TZ'] = 'Asia/Shanghai'
if hasattr(time, 'tzset'):
    time.tzset()

from app.routers import auth, users, shipment, config, sys_config
from app.core.security import get_current_active_user
from app.core.config import settings
from app.db.init_db import init_db
from app.utils.timezone_util import get_current_timestamp
from app.core.startup import startup_event, shutdown_event

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
)
logger = logging.getLogger(__name__)

app = FastAPI(
    title=settings.PROJECT_NAME,
    description="货物追踪系统API",
    version="1.0.0",
)

# 配置CORS
app.add_middleware(
    CORSMiddleware,
    allow_origins=settings.CORS_ORIGINS,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 统一响应格式的中间件
@app.middleware("http")
async def add_process_time_header(request: Request, call_next):
    start_time = time.time()
    response = await call_next(request)
    process_time = time.time() - start_time
    
    # 为响应添加处理时间头
    response.headers["X-Process-Time"] = str(process_time)
    
    # 只有当响应内容是JSON，且响应对象有body方法时才进行处理
    if (response.headers.get("content-type") == "application/json" and 
        hasattr(response, "body") and callable(getattr(response, "body", None))):
        try:
            content = await response.body()
            # 避免修改已经格式化的响应
            if not b'"code":' in content:
                body = {
                    "code": 200,
                    "message": "成功",
                    "data": content,
                    "timestamp": get_current_timestamp()
                }
                return JSONResponse(
                    status_code=response.status_code,
                    content=body
                )
        except Exception:
            # 如果出现错误，返回原始响应
            pass
    
    return response

# 请求验证错误处理
@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request: Request, exc: RequestValidationError):
    return JSONResponse(
        status_code=422,
        content={
            "code": 422,
            "message": f"参数校验错误: {str(exc)}",
            "data": None,
            "timestamp": get_current_timestamp()
        },
    )

# 全局异常处理
@app.exception_handler(Exception)
async def global_exception_handler(request: Request, exc: Exception):
    return JSONResponse(
        status_code=500,
        content={
            "code": 500,
            "message": f"服务器错误: {str(exc)}",
            "data": None,
            "timestamp": get_current_timestamp()
        },
    )

# 注册路由
app.include_router(auth.router, prefix="/api", tags=["认证管理"])
app.include_router(users.router, prefix="/api", tags=["用户管理"], dependencies=[Depends(get_current_active_user)])
app.include_router(config.router, prefix="/api/system", tags=["系统配置"], dependencies=[Depends(get_current_active_user)])
app.include_router(sys_config.router, prefix="/api/system", tags=["基础配置"], dependencies=[Depends(get_current_active_user)])
app.include_router(shipment.router, prefix="/api/cargoTracking", tags=["货物追踪"], dependencies=[Depends(get_current_active_user)])

@app.get("/api/health", tags=["健康检查"])
async def health_check():
    return {
        "code": 200,
        "message": "服务正常运行",
        "data": {"status": "healthy"},
        "timestamp": get_current_timestamp()
    }

# 添加启动和关闭事件
app.add_event_handler("startup", startup_event)
app.add_event_handler("shutdown", shutdown_event)
if __name__ == "__main__":
    import uvicorn
    uvicorn.run("main:app", host="0.0.0.0", port=8000, reload=True)